//
//  YYStatusPictureView.swift
//  YYWeibo
//
//  Created by strongwallyi on 16/1/4.
//  Copyright © 2016年 strongwallyi. All rights reserved.
//

import UIKit
import SDWebImage

//配图视图里面最大的列数
let YYStatusPictureMaxCol = 3

//可重用 id
private let YYStatusPictureCellId = "YYStatusPictureCellId"

//每一条目之间的间距
private let itemMargin: CGFloat = 5
//每一个条目的宽度以及高度
private let itemWH = CGFloat(Int((SCREENW - 2 * YYStatusCellMargin - 2 * itemMargin) / CGFloat(YYStatusPictureMaxCol)))

class YYStatusPictureView: UICollectionView, UICollectionViewDataSource {
    
    //定义属性,供外界设置数据
    var picUrls: [YYStatusPictureInfo]? {
        didSet{
            //设置数据
            //取出数量
            let count = picUrls?.count ?? 0
            //显示有多上胀图片
            countLabel.text = "\(count)"
            
            //根据有多少张图片去更新大小约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(calcViewSize(count))
            }
            //设置完数据更新约束
            reloadData()
        }
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        //backgroundColor = RandomColor()
        //设置数据源方法
        dataSource = self
        //注册 cell
        registerClass(YYStatusPictureViewCell.self, forCellWithReuseIdentifier: YYStatusPictureCellId)
        
        //设置每一个 cell 的大小
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        
        //设置列间距
        layout.minimumInteritemSpacing = itemMargin
        
        //行间距
        layout.minimumLineSpacing = itemMargin
        
        addSubview(countLabel)
        
        countLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    }
    
    //根据图片的张数,计算当前配图视图的大小
    private func calcViewSize(count: Int) -> CGSize {

        //只有一张图片的时候
        if count == 1{
            //key 就是图片的地址
            let key = picUrls!.first!.thumbnail_pic
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            //判断在缓存中是否有取出图片
            if image != nil{
                var size = image.size
                //过窄的处理
                if size.width < 80 {
                    let width: CGFloat = 80
                    let height = width / size.width * size.height
                    
                    size.width = width
                    //约束最大的高度
                    size.height = height > 150 ? 150 : height
                }else if size.width > 200 {
                    //图片过宽的处理
                    let width: CGFloat = 200
                    let height = width / size.width * size.height
                    
                    size.width = width
                    size.height = height
                }
                
                //更改 cell的大小
                let layout = collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = size
                return size
            }else{
                //没有取出来就直接返回正方形的 size
                return CGSize(width: itemWH, height: itemWH)
            }
        }else{
            let layout = collectionViewLayout as! UICollectionViewFlowLayout
            layout.itemSize = CGSize(width: itemWH, height: itemWH)
        }
        //计算列数
        var col = count > YYStatusPictureMaxCol ? YYStatusPictureMaxCol : count
        if count == 4{
            col = 2
            }
        
        //计算行数
        let row = (count - 1) / YYStatusPictureMaxCol + 1
        
        //计算宽度以及高度
        let width = CGFloat(col) * itemWH + CGFloat(col - 1) * itemMargin
        let height = CGFloat(row) * itemWH + CGFloat(row - 1) * itemMargin
        
        return CGSize(width: width, height: height)
    }
    
    //做测试用,显示当前配图中有多少图片
    private lazy var countLabel: UILabel = {
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 35)
        return label
    }()
}

//collectionview 的数据源方法
extension YYStatusPictureView {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YYStatusPictureCellId, forIndexPath: indexPath) as! YYStatusPictureViewCell
        
        //设置数据
        cell.picUrl = picUrls![indexPath.item]
        return cell
    }
}

//自定义 cell
private class YYStatusPictureViewCell: UICollectionViewCell {
    
    //定义外界设置的属性
    var picUrl: YYStatusPictureInfo? {
        didSet{
            if let urlString = picUrl?.thumbnail_pic {
                let url = NSURL(string: urlString)
                //从网络请求图片且显示图片
                imageView.sd_setImageWithURL(url, placeholderImage: UIImage(named: "timeline_image_placeholder"))
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        contentView.addSubview(imageView)
        //添加约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
    }

    //懒加载控件
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //图片的样式
        imageView.contentMode = .ScaleAspectFill
        //截取掉超出的部分
        imageView.clipsToBounds = true
        return imageView
    }()
}



